var QQMapWX = require("../../libs/qqmap-wx-jssdk.js");
var qqmapsdk;
const app = getApp();
const util = require('../../utils/util.js');
import {
    TIM,
    COS,
    tim
} from '../../message/message.js';
let onMessageReceived = function (event) {
    console.log('您有新的消息，请注查收')
};
tim.on(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived);
Page({
    data: {
        imageUrl: app.globalData.imageUrl,
        dataList: [],
        list: 'goods_list',
        address: '',
        show_fly_img: false,
        goodsImageFly: '',
        cartGoods: {},
        official_mask: false,
        bottomIndex: 0,
        curpage: 1,
        hasmore: true,
        goods_list: [],
        bottomDataCode: '',
        bottomType: '',
        key: '',
        isScrolling: false,
        scrollTop: 0,
        menuClass: 0,
        showAllmenu: false
    },
    officialLoad: function (e) {
        if (e.detail.status == 0) {
            this.setData({
                official_mask: true,
            })
        }
    },
    officialHide: function () {
        this.setData({
            official_mask: false,
        })
    },

    onLoad: function (options) {
        //请求分享数据
        wx.request({
            url: app.globalData.ApiUrl + '/index.php?act=wx_share&op=get_share',
            data: {},
            method: 'GET',
            dataType: 'json',
            success: res => {
                if (res.data.code == '200') {
                    this.setData({
                        share_default_title: res.data.datas.title,
                        share_default_image_url: res.data.datas.imageUrl
                    })
                }
            }
        })
        util.share();
        // 实例化API核心类
        qqmapsdk = new QQMapWX({
            key: 'FS4BZ-HINKW-7XBRR-OLZ5Y-PLPF6-5CF5J'
        });
        var self = this;
        wx.getStorage({
            key: 'key',
            success: (res) => {
                self.setData({
                    key: res.data,
                })
                this.getCartInfo();
            }
        });
        wx.getStorage({
            key: 'index_wechat_index',
            success: (res) => {
                if (Date.parse(new Date()) - res.data.cachTime > 900000) {
                    self.getRequest();
                } else {
                    self.show_datas(res.data.datas);
                }
            },
            fail: () => {
                //获取列表数据
                self.getRequest();
            }
        })
        wx.getLocation({
            type: 'gcj02',
            success: function (res) {
                wx.setStorage({
                    key: 'latitude',
                    data: res.latitude,
                })
                wx.setStorage({
                    key: 'longitude',
                    data: res.longitude,
                })
                qqmapsdk.reverseGeocoder({
                    location: {
                        latitude: res.latitude,
                        longitude: res.longitude
                    },
                    success: function (res) {
                        self.setData({
                            address: res.result.formatted_addresses.recommend
                        })
                        wx.setStorage({
                            key: 'address',
                            data: res.result.formatted_addresses.recommend
                        })
                    },
                    fail: function (res) {
                        console.log("获取地址失败")
                    }
                })
            },
        })
        this.cartPos = {};
        this.cartPos['x'] = app.globalData.sw - 99;
        this.cartPos['y'] = app.globalData.sh - 45;
    },
    onReady: function () {
        let self = this;
        setTimeout(() => {
            let selQuery = wx.createSelectorQuery();
            selQuery.select('.bottom-tab').boundingClientRect();
            selQuery.exec(res => {
                self.setData({
                    bottomTabTopFixed: res[0].top - 90
                })
            })
        }, 100);
    },
    getRequest: function () {
        var self = this
        wx.request({
            url: app.globalData.ApiUrl + '/index.php?act=wechat_index',
            success(res) {
                var data = res.data;
                data.cachTime = Date.parse(new Date());
                wx.setStorage({
                    key: 'index_wechat_index',
                    data: data
                })
                self.show_datas(data.datas);

            },
            complete: function () {
                wx.hideNavigationBarLoading() //完成停止加载
                wx.stopPullDownRefresh() //停止下拉刷新

            }
        })
    },
    show_datas: function (data) {
        var self = this
        for (var index in data) {
            switch (data[index].key) {
                case 'adv_list':
                case 'home3':
                case 'goods_class':
                    for (var i in data[index].value.item) {
                        data[index].value.item[i].url = util.buildUrl(data[index].value.item[i].type, data[index].value.item[i].data);
                    }

                    break;
                case "broad":
                    for (var i in data[index].value.list) {
                        data[index].value.list[i].url = util.buildUrl(data[index].value.list[i].type, data[index].value.list[i].data);
                    }

                    break;
                case 'home1':
                    data[index].value.url = util.buildUrl(data[index].value.type, data[index].value.data);
                    break;

                case 'home2':
                case 'home4':
                    data[index].value.square_url = util.buildUrl(data[index].value.square_type, data[index].value.square_data);
                    data[index].value.rectangle1_url = util.buildUrl(data[index].value.rectangle1_type, data[index].value.rectangle1_data);
                    data[index].value.rectangle2_url = util.buildUrl(data[index].value.rectangle2_type, data[index].value.rectangle2_data);
                    break;
                case 'home5':
                    data[index].value.url = util.buildUrl(data[index].value.type, data[index].value.data);
                    break;
                case 'home6':
                    data[index].value.rectangle1_url = util.buildUrl(data[index].value.rectangle1_type, data[index].value.rectangle1_data);
                    data[index].value.rectangle2_url = util.buildUrl(data[index].value.rectangle2_type, data[index].value.rectangle2_data);
                    data[index].value.rectangle3_url = util.buildUrl(data[index].value.rectangle3_type, data[index].value.rectangle3_data);
                    data[index].value.rectangle4_url = util.buildUrl(data[index].value.rectangle4_type, data[index].value.rectangle4_data);
                    data[index].value.rectangle5_url = util.buildUrl(data[index].value.rectangle5_type, data[index].value.rectangle5_data);
                    break;
                case 'home7':
                    data[index].value.rectangle1_url = util.buildUrl(data[index].value.rectangle1_type, data[index].value.rectangle1_data);
                    data[index].value.rectangle2_url = util.buildUrl(data[index].value.rectangle2_type, data[index].value.rectangle2_data);
                    data[index].value.rectangle3_url = util.buildUrl(data[index].value.rectangle3_type, data[index].value.rectangle3_data);
                    data[index].value.rectangle4_url = util.buildUrl(data[index].value.rectangle4_type, data[index].value.rectangle4_data);
                    break;
                case 'home8':
                    data[index].value.rectangle1_url = util.buildUrl(data[index].value.rectangle1_type, data[index].value.rectangle1_data);
                    data[index].value.rectangle2_url = util.buildUrl(data[index].value.rectangle2_type, data[index].value.rectangle2_data);
                    break;
                case 'home9':
                    data[index].value.rectangle1_url = util.buildUrl(data[index].value.rectangle1_type, data[index].value.rectangle1_data);
                    data[index].value.rectangle2_url = util.buildUrl(data[index].value.rectangle2_type, data[index].value.rectangle2_data);
                    data[index].value.rectangle3_url = util.buildUrl(data[index].value.rectangle3_type, data[index].value.rectangle3_data);
                    data[index].value.rectangle4_url = util.buildUrl(data[index].value.rectangle4_type, data[index].value.rectangle4_data);
                    break;
                case 'home10':
                    data[index].value.rectangle1_url = util.buildUrl(data[index].value.rectangle1_type, data[index].value.rectangle1_data);
                    data[index].value.rectangle2_url = util.buildUrl(data[index].value.rectangle2_type, data[index].value.rectangle2_data);
                    data[index].value.rectangle3_url = util.buildUrl(data[index].value.rectangle3_type, data[index].value.rectangle3_data);
                    data[index].value.rectangle4_url = util.buildUrl(data[index].value.rectangle4_type, data[index].value.rectangle4_data);
                    break;
                case 'home11':
                    data[index].value.rectangle1_url = util.buildUrl(data[index].value.rectangle1_type, data[index].value.rectangle1_data);
                    data[index].value.rectangle2_url = util.buildUrl(data[index].value.rectangle2_type, data[index].value.rectangle2_data);
                    data[index].value.rectangle3_url = util.buildUrl(data[index].value.rectangle3_type, data[index].value.rectangle3_data);
                    data[index].value.rectangle4_url = util.buildUrl(data[index].value.rectangle4_type, data[index].value.rectangle4_data);
                    data[index].value.rectangle5_url = util.buildUrl(data[index].value.rectangle5_type, data[index].value.rectangle5_data);
                    data[index].value.rectangle6_url = util.buildUrl(data[index].value.rectangle6_type, data[index].value.rectangle6_data);
                    break;
                case 'home12':
                    data[index].value.rectangle1_url = util.buildUrl(data[index].value.rectangle1_type, data[index].value.rectangle1_data);
                    data[index].value.rectangle2_url = util.buildUrl(data[index].value.rectangle2_type, data[index].value.rectangle2_data);
                    data[index].value.rectangle3_url = util.buildUrl(data[index].value.rectangle3_type, data[index].value.rectangle3_data);
                    break;
                case 'home13':
                    data[index].value.rectangle1_url = util.buildUrl(data[index].value.rectangle1_type, data[index].value.rectangle1_data);
                    data[index].value.rectangle2_url = util.buildUrl(data[index].value.rectangle2_type, data[index].value.rectangle2_data);
                    data[index].value.rectangle3_url = util.buildUrl(data[index].value.rectangle3_type, data[index].value.rectangle3_data);
                    data[index].value.rectangle4_url = util.buildUrl(data[index].value.rectangle4_type, data[index].value.rectangle4_data);
                    break;
                case "goods":
                    for (var i in data[index].value.item) {
                        data[index].value.item[i].url = '/pages/goods_detail/goods_detail?goods_id=' + data[index].value.item[i].goods_id;
                    }

                    break;
                case 'video_list':
            }
        }
        self.setData({
            dataList: data
        })
    },
    searchPage: function () {
        wx.redirectTo({
            url: '../search_new/search_new',
        })
    },

    onShow: function () {
        var self = this;
        wx.getStorage({
            key: 'address',
            success: function (res) {
                self.setData({
                    address: res.data
                })
            },
        });
        util.tabCalCartNum();
        if (this.data.key) {
            this.getCartInfo();
        }

        wx.getStorage({
            key: 'key',
            success: (res) => {
                //红包start
                var timestamp = Date.parse(new Date()) / 1000;
                wx.getStorage({
                    key: "packageTime",
                    success: function (rest) {
                        if ((timestamp - rest.data) > 43200) {
                            self.giftBag = self.selectComponent("#gift_bag");
                            self.giftBag.getPackage(res.data);
                        }
                    },
                    fail: function () {
                        self.giftBag = self.selectComponent("#gift_bag");
                        self.giftBag.getPackage(res.data);
                    }
                });
            }
        })
        wx.getStorage({
            key: 'index_wechat_index',
            success: (res) => {
                if (Date.parse(new Date()) - res.data.cachTime > 900000) {
                    self.getRequest();
                } else {
                    self.show_datas(res.data.datas);
                }
            },
            fail: () => {
                //获取列表数据
                self.getRequest();
            }
        })
        this.getBottomData();

    },
    //红包end
    addCart: function (e) {
        let self = this;
        let goods_id = e.currentTarget.dataset['goods_id'];
        let quantity = 1;
        let addQuantity = 0;
        let goods_img = e.currentTarget.dataset['goods_img'];
        if (this.data.cartGoods[goods_id]) {
            addQuantity = this.data.cartGoods[goods_id].goods_num * 1 + 1;
        } else {
            addQuantity = 1
        }
        this.setData({
            goodsImageFly: goods_img
        })
        wx.getStorage({
            key: 'key',
            success: (res) => {
                wx.request({
                    url: app.globalData.ApiUrl + '/index.php?act=member_cart&op=cart_add_edit',
                    data: {
                        key: res.data,
                        goods_id: goods_id,
                        quantity: addQuantity
                    },
                    method: 'POST',
                    header: {
                        'content-type': 'application/x-www-form-urlencoded'
                    },
                    dataType: 'json',
                    success: (res) => {
                        if (res.data.code == 200) {
                            wx.getStorage({
                                key: 'cart_count',
                                success: (res) => {
                                    wx.setTabBarBadge({
                                        index: 3,
                                        text: String(res.data + quantity)
                                    })
                                    wx.setStorage({
                                        key: 'cart_count',
                                        data: res.data + quantity
                                    })
                                },
                            })
                            self.addcartAnimation(e);
                            self.setData({
                                cart_count: self.data.cart_count + 1
                            })
                            if (this.data.cartGoods[goods_id]) {
                                self.data.cartGoods[goods_id].goods_num++;
                                self.setData({
                                    cartGoods: self.data.cartGoods
                                })
                            } else {
                                self.data.cartGoods[goods_id] = {
                                    cart_id: res.data.datas,
                                    goods_num: 1
                                }
                                self.setData({
                                    cartGoods: self.data.cartGoods
                                })
                            }

                        } else {
                            wx.showToast({
                                title: res.data.datas.error,
                                icon: 'none'
                            })
                        }
                    }
                });
            },
            fail: () => {
                if (app.globalData.authorized) {
                    wx.navigateTo({
                        url: "../chooselogin/chooselogin"
                    })
                } else {
                    wx.navigateTo({
                        url: "../login/login"
                    })
                }
            }
        })
    },
    cutCart: function (e) {
        var self = this;
        var quantity = 1;
        var price = e.currentTarget.dataset.price;
        var goods_id = e.currentTarget.dataset.goods_id;
        if (e.currentTarget.dataset.cart_id) {
            var cart_id = e.currentTarget.dataset.cart_id;
        } else {
            var cart_id = this.data.newCartGoods[goods_id];
        }
        if (this.data.cartGoods[goods_id].goods_num != 1) {
            wx.request({
                url: app.globalData.ApiUrl + '/index.php?act=member_cart&op=cart_add_edit',
                data: {
                    key: self.data.key,
                    goods_id: goods_id,
                    quantity: self.data.cartGoods[goods_id].goods_num * 1 - 1,
                },
                method: 'POST',
                header: {
                    'content-type': 'application/x-www-form-urlencoded'
                },
                success: res => {
                    this.data.cartGoods[goods_id].goods_num--;
                    this.data.cart_count--;
                    this.setData({
                        cartGoods: this.data.cartGoods,
                        cart_count: this.data.cart_count
                    })
                    wx.getStorage({
                        key: 'cart_count',
                        success: (res) => {
                            wx.setTabBarBadge({
                                index: 3,
                                text: String(res.data - quantity)
                            })
                            wx.setStorage({
                                key: 'cart_count',
                                data: res.data - quantity
                            })
                        },
                    })
                }
            })
        } else {
            wx.showModal({
                title: '温馨提示',
                content: '确定要删除该商品吗？',
                success: res => {
                    if (res.confirm) {
                        //调用删除接口
                        wx.request({
                            url: app.globalData.ApiUrl + '/index.php?act=member_cart&op=cart_del',
                            data: {
                                key: self.data.key,
                                cart_id: cart_id
                            },
                            method: 'POST',
                            header: {
                                'content-type': 'application/x-www-form-urlencoded'
                            },
                            dataType: 'json',
                            success: res => {
                                delete this.data.cartGoods[goods_id];
                                this.data.cart_count--;
                                this.setData({
                                    cartGoods: this.data.cartGoods,
                                    cart_count: this.data.cart_count
                                })
                                wx.getStorage({
                                    key: 'cart_count',
                                    success: (res) => {
                                        if (res.data > 1) {
                                            wx.setTabBarBadge({
                                                index: 3,
                                                text: String(res.data - 1)
                                            })
                                        } else {
                                            wx.removeTabBarBadge({
                                                index: 3,
                                            })
                                        }

                                        wx.setStorage({
                                            key: 'cart_count',
                                            data: res.data - 1
                                        })
                                    }
                                })
                            }
                        })
                    }
                }
            })
        }
    },
    getCartInfo: function () {
        var self = this;
        wx.request({
            url: app.globalData.ApiUrl + '/index.php?act=member_cart&op=cart_list',
            data: {
                key: self.data.key
            },
            method: 'POST',
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            dataType: 'json',
            success: res => {
                if (res.data.code == '200') {
                    self.setData({
                        cart_list: res.data.datas.cart_list
                    })
                    var selfGoods = {};
                    var arrtemp = new Array();
                    for (let i = 0; i < 20; i++) {
                        arrtemp[i] = new Object();
                    }
                    for (let i = 0; i < self.data.cart_list.length; i++) {
                        for (let j = 0; j < self.data.cart_list[i].goods.length; j++) {
                            selfGoods[self.data.cart_list[i].goods[j].goods_id] = {
                                cart_id: self.data.cart_list[i].goods[j].cart_id,
                                goods_num: self.data.cart_list[i].goods[j].goods_num
                            }
                        }
                    }
                    self.setData({
                        cartGoods: selfGoods
                    })
                }
            }
        })
    },
    preventTouchMove: function () {
        return false;
    },
    addcartAnimation: function (e) {
        if (this.data.show_fly_img)
            return;
        this.finger = {};
        var topPoint = {};
        this.finger['x'] = e.touches["0"].clientX - 100;
        this.finger['y'] = e.touches["0"].clientY - 145;
        if (this.finger['x'] - this.cartPos['x'] < 0) {
            topPoint['x'] = (this.cartPos['x'] - this.finger['x']) / 2 + this.finger['x'];
        } else {
            topPoint['x'] = Math.abs(this.cartPos['x'] - this.finger['x']) / 2 + this.cartPos['x'];
        }
        if (this.finger['y'] < this.cartPos['y']) {
            topPoint['y'] = this.finger['y'] - 80;
        } else {
            topPoint['y'] = this.cartPos['y'] - 80;
        }
        this.linePos = app.bezier([this.finger, topPoint, this.cartPos], 20);
        this.startAnimation();
    },
    startAnimation: function () {
        var index = 0,
            self = this,
            bezier_points = this.linePos['bezier_points'];
        this.setData({
            show_fly_img: true,
            fly_x: self.finger['x'],
            fly_y: self.finger['y']
        })
        this.timer = setInterval(() => {
            self.setData({
                fly_x: bezier_points[index]['x'],
                fly_y: bezier_points[index]['y']
            })
            index++;
            if (index >= 20) {
                clearInterval(self.timer);
                self.setData({
                    show_fly_img: false
                })
            }
        }, 16);
    },
    getBottomData: function () {
        let self = this;
        wx.request({
            url: app.globalData.ApiUrl + '/index.php?act=wechat_index&op=bottom_tab',
            method: 'GET',
            data: {
                curpage: self.data.curpage,
                key: self.data.key,
                type: self.data.bottomType,
                data: self.data.bottomDataCode
            },
            success: res => {
                if (res.data.code == 200) {
                    var data = res.data;
                    self.setData({
                        goods_list: self.data.goods_list.concat(data.datas.goods_list),
                        hasmore: data.hasmore
                    })
                    if (data.hasmore) {
                        self.data.curpage++
                    }
                }
            }
        })
    },
    getBottomRequest: function () {
        var self = this;

    },
    show_bottom_datas: function (data) {
        var self = this;
        self.setData({
            goods_list: self.data.goods_list.concat(data.datas.goods_list),
            hasmore: data.hasmore
        })
        if (data.hasmore) {
            self.data.curpage++
        }
    },
    switchBottom: function (e) {
        let self = this;
        this.data.curpage = 1;
        this.data.hasmore = true;
        this.data.goods_list = [];
        let index = e.currentTarget.dataset.index;
        let type = e.currentTarget.dataset.type;
        let datacode = e.currentTarget.dataset.datacode;
        this.setData({
            bottomIndex: index,
            bottomType: type,
            bottomDataCode: datacode
        })
        this.getBottomData();
        if (wx.pageScrollTo) {
            wx.pageScrollTo({
                scrollTop: self.data.bottomTabTopFixed
            })
        } else {
            wx.showModal({
                title: '提示',
                content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
            })
        }
    },
    onPageScroll: function (e) {
        let self = this;
        let selQuery = wx.createSelectorQuery();
        selQuery.select('.bottom-tab').boundingClientRect();
        selQuery.exec(res => {
            if (res[0].top > 0) {
                self.setData({
                    bottomTabTop: res[0].top,
                })
            }
            if (e.scrollTop <= self.data.bottomTabTopFixed) {
                self.setData({
                    scrollTop: e.scrollTop
                })
            }

        })
    },
    onReachBottom: function () {
        if (this.data.hasmore) {
            this.getBottomData()
        }
    },
    onPullDownRefresh: function () {
        wx.showToast({
            title: '加载中',
            icon: 'loading',
            duration: 400
        });
        let self = this;
        wx.getStorageInfo({
            success(res) {
                let arr = ["key", "username", "member_mobile", "cart_count", "packageTime", "_mta_ssid", "latitude", "longitude", "address", "share_key"];
                for (var i = 0; i < res.keys.length; i++) {
                    var inArray = self.in_array(res.keys[i], arr);
                    if (!inArray) {
                        wx.removeStorage({
                            key: res.keys[i],
                            success(res) { }
                        })
                    }
                }
            }
        })
        wx.showNavigationBarLoading() //在标题栏中显示加载
        this.getRequest();
    },
    in_array: function (search, array) {
        for (var i in array) {
            if (array[i] == search) {
                return true;
            }
        }
        return false;
    },
    goTOMore: function () {
        if (this.data.isScrolling === true)
            return;
        this.data.isScrolling = true;
        wx.navigateTo({
            url: '../xianshi/xianshi'
        })
        this.data.isScrolling = false;
    },
    goTOMoreSecondkill: function () {
        if (this.data.isScrolling === true)
            return;
        this.data.isScrolling = true;
        wx.navigateTo({
            url: '../secondkill/secondkill'
        })
        this.data.isScrolling = false;
    },
    goTOMoreNewgoods: function () {
        if (this.data.isScrolling === true)
            return;
        this.data.isScrolling = true;
        wx.navigateTo({
            url: '../new_goods/new_goods'
        })
        this.data.isScrolling = false;
    },
    goTop: function (e) { // 一键回到顶部
        if (wx.pageScrollTo) {
            wx.pageScrollTo({
                scrollTop: 0
            })
        } else {
            wx.showModal({
                title: '提示',
                content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
            })
        }
    },
    changeMenuClass: function (e) {
        let index = e.currentTarget.dataset.index;
        let class_id = e.currentTarget.dataset.class_id;
        if (index <= 2) {
            this.setData({
                curClassIndex: 0
            })
        } else {
            this.setData({
                curClassIndex: index - 2
            })
        }
        this.setData({
            menuClass: index,
            showAllmenu: false
        })
        wx.navigateTo({
            url: `../menu_list/menu_list?class_id=${class_id}&index=${index}`
        })
    },
    showAllMenuClass: function () {
        this.setData({
            showAllmenu: !this.data.showAllmenu
        })
    },
    onShareAppMessage: function () {
        let share_key = this.data.key ? this.data.key : '';
        let share_path = '';
        if (util.getCurrentPageUrlWithArgs().indexOf("?") != -1) {
            share_path = util.getCurrentPageUrlWithArgs() + '&share_key=' + share_key;
        } else {
            share_path = util.getCurrentPageUrlWithArgs() + '?share_key=' + share_key;
        }
        return {
            title: this.data.share_default_title,
            imageUrl: this.data.share_default_image_url,
            path: share_path
        }
    }
})